<?php set_time_limit(0);?>
<?php include '_init_.php';?>
<?php include 'page_header.php';?>
<?
 if(SessionUtil::isExistVar(constant('SESSION_KEY_USER_ID')) && 
				(SessionUtil::getVar(constant('SESSION_KEY_USER_IS_ADMIN')) == 'Y'
				))
				{
				}else{
				exit("Not allowed!");
				}
?>
<div id="main"><!-- start #main //-->
<div id="tita"> <!-- start #tita //-->
<div id="tita"> <!-- start #tita //-->
<div class="tita-1">
    <h3>匯入訂單</h3>
    </div>
  <div class="tita-2">
  </div>
</div>

<?php

?>
<form action="import.php" enctype="multipart/form-data" method="post">
<div id="mainf" class="clearfix"><!-- start #maine //-->
<div class="mainf-3">
<ul>
      <li>
       上傳CSV档案：<input name="file" type="file" id="file"/>
       <input type="submit" value="匯入"/>
       </li>
       </ul>
   
     </div>
   
     </div><!-- end #maine //-->
     </form>
</div><!-- end #main //-->
<?php
if(isset($_FILES["file"]))
{
 if ( ! $_FILES["file"]["name"]){
 	echo "請選擇CSV档案";
 }else{
 if ($_FILES["file"]["error"] > 0)
  {
  	echo "Error: " . $_FILES["file"]["error"] . "<br />";
  }
	else
  {
  	/*
     echo "Upload: " . $_FILES["file"]["name"] . "<br />";
     echo "Type: " . $_FILES["file"]["type"] . "<br />";
      echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
      echo "Stored in: " . $_FILES["file"]["tmp_name"];
      */
      $ext = Util::getFileExt($_FILES["file"]["name"]);
      if(strtolower($ext) != 'csv'){
      	echo "請上傳CSV档案";
      }else{
         $csv_path = constant('PATH_ORDER_EDITING_DIR').'/import_'.time().'.csv';
          move_uploaded_file($_FILES["file"]["tmp_name"],$csv_path);
         
          define('DATA_CHAR_ENCODE','UTF-8');
		 //define('CLIENT_CSV_ENCODE','gbk');
		 define('CLIENT_CSV_ENCODE','cp950');
		 $csv_content = file_get_contents($csv_path);
		 $begin_key_character = mb_convert_encoding('開單日期', constant('CLIENT_CSV_ENCODE'), constant('DATA_CHAR_ENCODE'));
		 $begin_index = strpos($csv_content, $begin_key_character);
		 $csv_format_type = 1;
		 if (  $begin_index === FALSE ) {
		 	$begin_key_character = mb_convert_encoding('日  期', constant('CLIENT_CSV_ENCODE'), constant('DATA_CHAR_ENCODE'));
		 	$begin_index = strpos($csv_content, $begin_key_character);
		 	 $csv_format_type = 2;
		 }
		 if (  $begin_index === FALSE ) {
		 echo '上傳CSV档案格式錯誤';
		 exit();
		 }
		 $csv_content = substr($csv_content, $begin_index);
		 $csv_content = mb_convert_encoding($csv_content,constant('DATA_CHAR_ENCODE'), constant('CLIENT_CSV_ENCODE'));
		 file_put_contents($csv_path, $csv_content);
		  $fh = fopen($csv_path,"r");
		  echo "<div style='width:700px;height:400px;overflow:scroll;'>";
		  echo "<table cellspacing=5>";
		  $row_index = 0;
		  setlocale(LC_ALL,'en_US.UTF-8');
          while($csv_row = fgetcsv($fh)){
            if ( empty($csv_row[1])) {
               continue;
            }
          	echo "<tr>";
          	if ( $row_index == 0 ) {
          		//print_r($csv_row);
          		echo "<td></td>";
          	}else{
          		//we only need to hand this case, othwise in class.datatable.php can escape string
          		if (get_magic_quotes_gpc())
          		{
          			foreach($csv_row as $tmp_row_index=>$tmp_row_value){
          				$csv_row[$tmp_row_index] = mysql_real_escape_string($tmp_row_value);
          			}
          		}
          		$om = new Order_Manager(false,false,false,false,false);
          		$o_number_taken = $om->isOrderNumberTaken($csv_row[1]);
          		if ($o_number_taken){
          			echo "<td nowrap><span style='color:#cccccc'>已存在的訂單不需要匯入</span></td>";
          		}else{
          		$orderManager = Order_Manager::createOrderManager();
          		$orderManager->init();
          		if ( $csv_format_type  == 1 ) {
          		$customer_info = array();
          		//customer data
          		$customer_info['name'] = $csv_row[14];
          		$birthdate = $csv_row[15];
          		if ( strlen($birthdate) > 0 ) {
          			
          			$token_list = explode('.',$birthdate);
          			$customer_info['birthday_year'] = $token_list[0];
          			$customer_info['birthday_month'] = $token_list[1];
          			$customer_info['birthday_date'] = $token_list[2];
          			
          		}
          		$customer_info['address_part_one'] = $csv_row[17];
          		$customer_info['tel_part_one'] = $csv_row[18];
          		$customer_info['mobile'] = $csv_row[20];
				$orderManager->setCustomerInfo($customer_info);
				//main info
				$main_info = array();
				$main_info['number'] = $csv_row[13];
				$main_info['department'] = $csv_row[4];
				$main_info['department_worker'] = $csv_row[5];
				$orderManager->setMainInfo($main_info, true, false);
			
				//price info
				$price_info = array();
				$price_info['total'] = $csv_row[6];
				$price_info['pre_pay'] = $csv_row[7];
				$price_info['need_pay'] = $csv_row[8];
				if ( strpos($price_info['total'], ',') !== FALSE){
					$price_info['total'] = preg_replace('/,/','',$price_info['total']);
					
				}
				
				$price_info['discountPrice'] = 0;
				$orderManager->setPayInfo($price_info);
				//work flow info
				$workflow_info = array();
				if ( importStrtotime($csv_row[8])) {
				$workflow_info['photo_time'] = date('Y-m-d',importStrtotime($csv_row[8]));
				}else{
					//$workflow_info['photo_time']  = '';
				}
				if ( importStrtotime($csv_row[10])) {
				$workflow_info['pickup_time'] = date('Y-m-d',importStrtotime($csv_row[10]));
				}else{
					//$workflow_info['pickup_time']  ='';
				}
				$orderManager->setWorkflowInfo($workflow_info);
				//note
				$orderManager->addNote($csv_row[11]);
				}else if ( $csv_format_type  == 2 ) {
				$customer_info = array();
          		//customer data
          		$customer_info['name'] = $csv_row[14];
          		$birthdate = $csv_row[15];
          		if ( strlen($birthdate) > 0 ) {
          			
          			$token_list = explode('.',$birthdate);
          			$customer_info['birthday_year'] = $token_list[0];
          			$customer_info['birthday_month'] = $token_list[1];
          			$customer_info['birthday_date'] = $token_list[2];
          			
          		}
          		$customer_info['address_part_one'] = $csv_row[16];
          		$customer_info['tel_part_one'] = $csv_row[17].' '.$csv_row[18];
          		$customer_info['mobile'] = $csv_row[19];
				$orderManager->setCustomerInfo($customer_info);
				//main info
				$main_info = array();
				$main_info['number'] = $csv_row[13];
				$main_info['department'] = $csv_row[3];
				$main_info['department_worker'] = $csv_row[4];
				$orderManager->setMainInfo($main_info, true, false);
			
				//price info
				$price_info = array();
				$price_info['total'] = $csv_row[6];
				$price_info['pre_pay'] = $csv_row[7];
				$price_info['need_pay'] = $csv_row[8];
				if ( strpos($price_info['total'], ',') !== FALSE){
					$price_info['total'] = preg_replace('/,/','',$price_info['total']);
					
				}
				
				$price_info['discountPrice'] = 0;
				$orderManager->setPayInfo($price_info);
				//work flow info
				$workflow_info = array();
				if ( importStrtotime($csv_row[8])) {
				$workflow_info['photo_time'] = date('Y-m-d',importStrtotime($csv_row[8]));
				}else{
					//$workflow_info['photo_time']  = '';
				}
				if ( importStrtotime($csv_row[10])) {
				$workflow_info['pickup_time'] = date('Y-m-d',importStrtotime($csv_row[10]));
				}else{
					//$workflow_info['pickup_time']  ='';
				}
				$orderManager->setWorkflowInfo($workflow_info);
				//note
				$orderManager->addNote($csv_row[11]);
				}
				//create date
				$orderCreateDate = importStrtotime($csv_row[0]);
				if ( $orderCreateDate  ) {
					$orderManager->setOrderCreateDate(date('Y-m-d',$orderCreateDate));
				}
				$orderManager->persistOrderInfo();
				
				$orderManager->injectOrderMainIndex();
				
				if ( isset($workflow_info['photo_time']) && strlen($workflow_info['photo_time'] ) > 0) {
					$orderManager->setOrderStatus('close');
					$orderManager->persistOrderInfo();
				}
				echo "<td nowrap><span style='color:blue'>匯入成功</span></td>";
				}
          	}
          	foreach( $csv_row as $column){
          		echo "<td nowrap>".$column."</td>";
          	}
          	echo "</tr>";
          	
          	  $row_index++;
          }
          echo "</table>";
           echo "</div>";
           
           unlink($csv_path);
      }
  }
  
  }
  
}else{
  	echo "請選擇CSV档案";
}

function importStrtotime($str)
{
$time = false;
$str = preg_replace('/\./','-',$str);
$str = preg_replace('/\-$/','',$str);
$str_token = explode('.',$str);
if ( count($str_token) > 0 && strlen(trim($str_token[0])) == 2) {
	$year = intVal($str_token[0]);
	$e_year = intVal(date('y'));
	if ( $year > $e_year) {
		$str  = '19'.$str;
	}else{
		$str  = '20'.$str;
	}
}
$time = strtotime($str);
return $time;
}
?>

</div><!-- end #all //-->

</body>
</html>